package controller.link.game;

import view.client.Console;
import model.Hearer;
import java.io.Serializable;
import controller.Link;
import controller.link.RefreshGameData;
import javax.swing.JOptionPane;
import model.game.Item;
import model.game.Place;
import model.game.Player;
import model.game.Scenario;
import model.game.Seller;
import model.Attendant;
import model.Server;
import model.game.Location;

public class BuyItem implements Link, Serializable {
    private String nameItem;
    private String message;
    public BuyItem() {
    }

    public BuyItem(Hearer h, String nameItem) {
        this.nameItem = nameItem;
        h.send((Link) this);
    }

    @Override
    public void serverUse(Server server, Attendant at) {
        Player player = at.getUser().getPlayer();        
        Location o = server.getWorld().getMap().whereIsPlayer(at.getUser().getName());
        for (int i=0; i<o.getNpcs().size(); i++){
                if (o.getNpcs().get(i)instanceof Seller){
                    for (int j=0; j<o.getNpcs().get(i).getItems().size(); j++){
                        if (o.getNpcs().get(i).getItems().get(j).getName().equals(nameItem)){
                            Item item = o.getNpcs().get(i).getItems().get(j);
                            if (player.setMoney(player.getMoney()-item.getPrice())){
                                player.addItem(item.changeOwner(player));
                                RefreshGameData rgd = new RefreshGameData();
                                rgd.serverUse(server, at);
                            }else{
                                message = "Você não tem dinheiro suficiente";
                                at.send((Link)this);
                            }
                        }
                    }
                }
            }
        
    }

    @Override
    public void clientUse(Console console) {
        JOptionPane.showMessageDialog(null, message);
    }
}